<script setup lang="ts" name="aiComponent">
import { ElMessage } from 'element-plus';
import { useElementSize } from '@vueuse/core';
import { baseUrl, mdTool, aiModelList } from '@/index';
import type { AiRequestType } from '@/index.d';
const divisionList: Array<string> = ['智能问答', '缺陷分析'];

const aiRequest = reactive<AiRequestType>({
  userMessage: '你是谁？',
  model: aiModelList[0],
  division: divisionList[0]
});

const replyData = ref<string>('');
const getAiDataLoading = ref<boolean>(false);
const replyDataContainer = useTemplateRef('replyDataContainer');
const { height } = useElementSize(replyDataContainer);

const getStreamText = async (url: string): Promise<string> => {
  if (aiRequest.userMessage.trim() === '') {
    ElMessage({
      message: '请输入内容后再提交',
      type: 'error'
    });
    return '请输入内容后再提交';
  }
  const response = await fetch(url, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(aiRequest)
  });
  if (!response.ok) {
    throw new Error(`HTTP error! status: ${response.status}`);
  }

  const reader = response.body?.getReader();
  if (!reader) {
    throw new Error('No reader available');
  }

  const decoder = new TextDecoder();
  let result = '';
  let str = '';
  try {
    while (true) {
      const { done, value } = await reader.read();
      if (done) break;
      str += decoder.decode(value, { stream: true });
      replyData.value = mdTool.render(str);
    }
  } finally {
    reader.releaseLock();
    getAiDataLoading.value = false;
  }
  return result;
};

const getAiInfo = () => {
  if (aiRequest.userMessage.trim() === '') {
    ElMessage({
      message: '请输入内容后再提交',
      type: 'error'
    });
    return false;
  }
  replyData.value = '';
  getAiDataLoading.value = true;
  getStreamText(baseUrl.value + '/ndeReport/rejectPart/ai/chat');
};
</script>
<template>
  <div class="ai-container">
    <div class="ai-container-item ai-container-body">
      <el-card shadow="hover" class="ai-container-body-reply">
        <template #header>{{ aiRequest.division + '：' + aiRequest.userMessage }} </template>
        <template #default>
          <div ref="replyDataContainer" class="ai-container-body-reply-content">
            <el-scrollbar :height="height">
              <div v-html="replyData" class="ai-container-body-reply-content-inner"></div>
            </el-scrollbar>
          </div>
        </template>
        <template #footer>
          共生成 <span style="color: red">{{ replyData.length }}</span> 字
        </template>
      </el-card>
      <el-card shadow="hover" class="ai-container-body-prompt">
        <template #header>
          <el-radio-group v-model="aiRequest.model">
            <el-radio v-for="item in aiModelList" :key="item" :value="item" :label="item" />
          </el-radio-group>
        </template>
        <template #default>
          <el-input
            v-model="aiRequest.userMessage"
            :readonly="getAiDataLoading"
            placeholder="请输入提示词语，按回车键执行。"
            @keydown.enter="getAiInfo"
            size="large"
          />
        </template>
        <template #footer>
          <el-button
            @click="getAiInfo"
            :loading="getAiDataLoading"
            style="width: 100%"
            type="primary"
          >
            {{ getAiDataLoading ? '正在思考' : '开始思考' }}
          </el-button>
        </template>
      </el-card>
    </div>
    <div class="ai-container-item ai-container-navy">
      <el-card shadow="hover">
        <template #header>功能选择</template>
        <template #default>
          <el-radio-group v-model="aiRequest.division">
            <el-radio-button v-for="item in divisionList" :key="item" :value="item" :label="item" />
          </el-radio-group>
        </template>
      </el-card>
    </div>
  </div>

  <div class="card-container"></div>
</template>
<style scoped lang="scss">
.ai-container {
  width: 100%;
  height: 100%;
  display: flex;

  .ai-container-item {
    display: flex;
    flex-direction: column;
    padding: 10px;
  }

  .ai-container-body {
    padding-right: 5px;
    flex: 5;

    .ai-container-body-reply {
      flex: 1;
      margin-bottom: 10px;
      .ai-container-body-reply-content {
        height: 100%;
        line-height: 2;
        font-size: 1rem;
        .ai-container-body-reply-content-inner {
          padding: 40px 40px;
        }
      }
    }
  }

  .ai-container-navy {
    flex: 1;
    padding-left: 5px;
    .el-card {
      width: 100%;
      height: 100%;
      overflow: hidden;
      // :deep(.el-card__body) {
      //   height: 100%;
      // }
    }
  }
}
</style>
